//
//  ViewController.m
//  文件续传
//
//  Created by 董文博 on 15/1/29.
//  Copyright (c) 2015年 OA. All rights reserved.
//

#import "DownloadViewController.h"

@interface DownloadViewController ()<NSURLConnectionDataDelegate>
@property(nonatomic,strong) NSFileHandle *handle;
@property(nonatomic,assign)long long fileLength;
@property(nonatomic,assign)long long currentFileLength;
@property(nonatomic,strong)NSURLConnection *conn;
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@property (weak, nonatomic) IBOutlet UIProgressView *progress;
@property (weak, nonatomic) IBOutlet UIButton *downLoadBtn;
@property (strong,nonatomic) NSMutableData *data;
@property (strong,nonatomic)NSMutableURLRequest *request;
@end

@implementation DownloadViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.handle = nil;
    self.conn = nil;
    self.data = nil;
}
- (IBAction)downLoad:(UIButton *)sender {
    NSURL *url = [NSURL URLWithString:@"http://fa.topit.me/a/d8/20/119867884294d20d8ao.jpg"];
        self.request = [[NSMutableURLRequest alloc] initWithURL:url];
    self.request.cachePolicy = NSURLCacheStorageNotAllowed;
    if([self.downLoadBtn.currentTitle  isEqual: @"下载"])
    {
        
        self.conn = [NSURLConnection connectionWithRequest:self.request delegate:self];
        [self.downLoadBtn setTitle:@"暂停" forState:(UIControlStateNormal)];
    }else if ([self.downLoadBtn.currentTitle isEqual:@"暂停"])
    {
        [self.conn cancel];
        self.conn = nil;
        [self.downLoadBtn setTitle:@"继续" forState:(UIControlStateNormal)];
    }else if([self.downLoadBtn.currentTitle isEqual:@"继续"])
    {
        NSString *value = [NSString stringWithFormat:@"bytes=%lld-", self.currentFileLength];
        [self.request setValue:value forHTTPHeaderField:@"Range"];
        self.conn = [NSURLConnection connectionWithRequest:self.request delegate:self];
        [self.downLoadBtn setTitle:@"暂停" forState:(UIControlStateNormal)];
    }
    
}

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    if (self.currentFileLength) {
        return;
    }
    self.data = [NSMutableData data];
    NSString *cache = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    NSString *path = [cache stringByAppendingPathComponent:@"app.zip"];
    NSFileManager *mgr = [NSFileManager defaultManager];
    [mgr createFileAtPath:path contents:nil attributes:nil];
    self.handle = [NSFileHandle fileHandleForWritingAtPath:path];
    self.fileLength = response.expectedContentLength;
}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    self.currentFileLength += data.length;
    self.progress.progress = (double)self.currentFileLength / self.fileLength;
    [self.data appendData:data];
    [self.imageView setImage:[UIImage imageWithData:self.data]];
    [self.handle seekToEndOfFile];
    [self.handle writeData:data];
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    [self.downLoadBtn setTitle:@"完成" forState:(UIControlStateNormal)];
    self.downLoadBtn.userInteractionEnabled = NO;
    UIAlertView *av = [[UIAlertView alloc] initWithTitle:nil message:@"下载完成!" delegate:nil cancelButtonTitle:@"好" otherButtonTitles:nil, nil];
    [av show];
}

-(void)dealloc
{
    self.conn = nil;
    self.request = nil;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
